package com.yokead.common;

import org.apache.commons.io.FileUtils;

import java.io.*;

/**
 * Created by jiangzeyin on 2017/12/14.
 */
public class EncodeFileUtil {

    public static String convert(File file, String targetCharset) throws IOException {
        // 如果是文件则进行编码转换，写入覆盖原文件
        String encode = EncodingDetect.getJavaEncode(file.getPath());
        if (targetCharset.equalsIgnoreCase(encode))
            return file.getPath();
        if (!file.isFile())
            throw new IllegalArgumentException(file.getPath() + " not file");
        String context = FileUtils.readFileToString(file, encode);
        File targetFile = new File(file.getPath() + "." + targetCharset);
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(targetFile), targetCharset);
        BufferedWriter bw = new BufferedWriter(osw);
        // 以字符串的形式一次性写入
        bw.write(context);
        bw.close();
        osw.close();
        return targetFile.getPath();
    }
}